<?php

define('ONLINE_DURATION', 600);

class online{
	protected $db;
	protected $ip;
	protected $ua;
	protected $uri;
	protected $hash;
	protected $refer;
	//can add it;
	protected $click;

	function __construct()
	{
		$this->ip = mysql_real_escape_string($_SERVER['REMOTE_ADDR']);
		$this->ua = mysql_real_escape_string($_SERVER['HTTP_USER_AGENT']);
		if (empty($_SERVER['REQUEST_QUERY']))
			$this->uri = mysql_real_escape_string($_SERVER['REQUEST_URI']);
		else
			$this->uri = mysql_real_escape_string($_SERVER['REQUEST_URI'].'?'.$_SERVER['REQUEST_QUERY']);
		$this->refer = mysql_real_escape_string($_SERVER['HTTP_REFERER']);
		$this->hash = mysql_real_escape_string(session_id());
		//$this->db = new mysqli(DBHOST, DBUSER, DBPASSWORD, )

		if($this->exist()){
			$this->update();
		}else{
			$this->addRecord();
		}
		
		$this->clean();
	}
	function getAll()
	{
		$ret = array();
		
		$sql = 'SELECT * FROM online';
		$res = mysql_query($sql);
		while($rt = mysql_fetch_object($res)) $ret[] = $rt;
		mysql_free_result($res);
		return $ret;
	}

	function getRecord($ip)
	{
		$sql = "SELECT * FROM online WHERE ip = '$ip'";
		$res = mysql_query($sql);
		if(mysql_num_rows($res)){
			$ret = mysql_fetch_object($res);
		}else{
			return false;
		}
		mysql_free_result($res);
		return $ret;
	}
	function get_num()
	{
		$sql = 'SELECT count(ip) as nums FROM online';
		$res = mysql_query($sql);
		$ret = mysql_fetch_object($res);
		mysql_free_result($res);
		return $ret->nums;
	}
	function exist()
	{
		$sql = "SELECT * FROM online WHERE hash = '$this->hash'";
		$res = mysql_query($sql);
		if(mysql_num_rows($res) == 0){
			return false;
		}else{
			return true;
		}
	}
	function addRecord()
	{
		$now = time();
		$sql = "INSERT INTO online(hash, ip, ua, uri, refer, firsttime, lastmove)
				VALUES ('$this->hash', '$this->ip', '$this->ua', '$this->uri', '$this->refer', '$now', '$now')";
		mysql_query($sql);
	}

	function update()
	{
		$sql = "UPDATE online
				SET
					ua = '$this->ua',
					uri = '$this->uri',
					refer = '$this->refer',
					lastmove = '".time()."',
					ip = '$this->ip'
				WHERE
					hash = '$this->hash'
				";
//		print($sql);
		mysql_query($sql);
	}
	function clean()
	{
		$sql = 'DELETE FROM online WHERE lastmove<' . (time()-ONLINE_DURATION);
		mysql_query($sql);
	}
}
